package com.nervenets.web.adapter;

import com.google.gson.*;
import com.nervenets.i18n.Translator;

import java.lang.reflect.Type;

/**
 * todo:必须要在com.nervenets.enumeration包名下面才可以
 * Created by joe on 17-3-15.
 */
public class EnumSerializer implements JsonSerializer<Enum>, JsonDeserializer<Enum> {

    @Override
    public Enum deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (!json.isJsonObject()) return null;
        JsonObject jsonObject = json.getAsJsonObject();
        String className = jsonObject.get("class").getAsString();
        String value = jsonObject.get("value").getAsString();
        try {
            Class<Enum> enumClass = (Class<Enum>) Class.forName("com.nervenets.web.enumeration." + className);
            Enum[] enums = enumClass.getEnumConstants();
            for (Enum anEnum : enums) {
                if (value.equals(anEnum.name())) {
                    return anEnum;
                }
            }
        } catch (Exception cnfe) {
            //throw new HibernateException("Enum class not found", cnfe);
        }
        return null;
    }

    @Override
    public JsonElement serialize(Enum src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject object = new JsonObject();
        object.addProperty("class", src.getClass().getSimpleName());
        object.addProperty("value", src.name());
        object.addProperty("text", Translator.translate(src));
        return object;
    }
}
